﻿class Region {
    constructor(startX, startY, width, height) {
        this.startX = startX;
        this.startY = startY;
        this.width = width;
        this.height = height;
    }
}

let CanvaseId = null; //Canvas id
let isDrawing = false; // 是否正在绘制新矩形的标志  
let currentRect = null; // 当前正在绘制的矩形
let isCanDraw = false;//是否可以画

export function initCanvasDrawRect(dotnetHelper, canvaseId, IsCanDraw) {
    CanvaseId = canvaseId;
    isCanDraw = IsCanDraw;
    var canvas = document.getElementById(canvaseId);
    canvas.addEventListener('mousedown', canvasmousedown);

    canvas.addEventListener('mousemove', function (e) {
        if (!isCanDraw)
            return;
        if (!isDrawing) return;

        const width = e.offsetX - currentRect.startX;
        const height = e.offsetY - currentRect.startY;
        currentRect.width = width;
        currentRect.height = height;
        draw(); // 更新并绘制当前矩形
    });



    canvas.addEventListener('mouseup', function (e) {
        isDrawing = false;
        if (currentRect && currentRect.width === 0 && currentRect.height === 0) {
            currentRect = null;
        }
    });

}

function canvasmousedown(e) {

    if (!isCanDraw)
        return;
    isDrawing = true;
    var canvas = document.getElementById(CanvaseId);
    const rect = canvas.getBoundingClientRect();
    const x = e.offsetX; //e.clientX - rect.left;
    const y = e.offsetY; //e.clientY - rect.top;
    currentRect = new Region(x, y, 0, 0);
    draw(); // 绘制初始矩形（只是一个点） 
}

export function clearCanvas() {
    var canvas = document.getElementById(CanvaseId);
    var ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    currentRect = null;
    isCanDraw = false;
}



function draw() {
    var canvas = document.getElementById(CanvaseId);
    var ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布上的内容


    if (currentRect && currentRect.width !== 0 && currentRect.height !== 0) {
        drawRect(currentRect); // 绘制当前矩形  
    }
}

function drawRect(rect) {
    var canvas = document.getElementById(CanvaseId);
    var ctx = canvas.getContext('2d');
    ctx.beginPath();
    ctx.lineWidth = 2; // 例如，使用更宽的线宽  
    ctx.strokeStyle = 'red'; // 使用红色边框  
    ctx.rect(rect.startX, rect.startY, rect.width, rect.height);
    ctx.stroke();
}

//获取所有图形
export function GetCurretnRectangle() {
    return currentRect;
}